<?php

class _F_EXTENSION_STYLE_ extends _F_EXTENSION_ {
	
	public $prev_callback;
	public $styles = array(); 
	public $default_style_attrs = array('rel' => 'stylesheet');

	public function __construct() {
		f()->register_method('style',array($this,'style'));
		$this->prev_callback = f()->register_method(
			'post_process_callback',array($this,'_f_callback_'));
	}
	
	// TODO: itt vilagos es egyseges szabalyok kellenek
	//
	// 1. ami '/' jellel kezdodik az relativ a {base_path}-hoz kepest
	//
	// 2. ami '@' jellel kezdodik az a kovetkezo modon lesz feldolgozva:
	//		- ha letezik base_path/$theme/styles/{file} akkor az
	//		- ha letezik base_path/styles/{file} akkor az
	// 		- figyelmeztetest kuld es erintetlenul kerul be
	//
	// 3. minden mas erintetlenul kerul be a cuccosba
	
	public function style($style = null, $attr = null) {
		if (func_num_args() > 0) {
			if ($style{0} == '@') {
				$file = '/styles/'.substr($style,1);
				$style = '/themes/'.f()->theme.$file;
				if (!file_exists(f()->base_path.$style)) $style = $file;
				if (!file_exists(f()->base_path.$style)) 
					error_log("VerSimF Notice: Style '$style' does not exist.");
			}
			$this->styles[$style] = null;
		}
		return $this;
	}

	public function _f_callback_() {
		if (isset($this->prev_callback)) call_user_func($this->prev_callback);
		$buffer = '';
		foreach ($this->styles as $style => $params) {
			$attr = $this->default_style_attrs;
			$attr['href'] = f()->url($style);
			if (isset($params)) $attr = array_merge($attr,$params);
			$attr =	f()->attr($attr);
			$buffer .=  "<link$attr/>\r\n";
		}
		f()->content = preg_replace('/<\/head>/im',"$buffer</head>",f()->content);
	}

}

new _F_EXTENSION_STYLE_;